package com.css.fxfzypg.modules.resultsManagement.service.impl;

import com.css.fxfzypg.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreVo;
import com.css.fxfzypg.modules.resultsManagement.entity.MapManagementEntity;
import com.css.fxfzypg.modules.resultsManagement.queryParams.MapManagementQueryParams;
import com.css.fxfzypg.modules.resultsManagement.repository.MapManagementRepository;
import com.css.fxfzypg.modules.resultsManagement.service.MapManagementService;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MapManagementServiceImpl implements MapManagementService {
    @Resource
    MapManagementRepository mapManagementRepository;
    @Resource
    SUserService sUserService;
    @Resource
    MapManagementService mapManagementService;
    @Resource
    PreAssessTaskRepository preAssessTaskRepository;
    @Resource
    AttachmentInfoService attachmentInfoService;

    @Override
    public String saveMap(MapManagementEntity mapManagementEntity) {
        MapManagementEntity managementEntity = mapManagementRepository.getByLabel(mapManagementEntity.getTaskId(), mapManagementEntity.getMapLabel());
        if (managementEntity != null) {
            mapManagementEntity.setMapId(managementEntity.getMapId());
            mapManagementEntity.setCreateUser(managementEntity.getCreateUser());
            mapManagementEntity.setCreateTime(managementEntity.getCreateTime());
            MapManagementEntity entity = mapManagementService.update(mapManagementEntity);
            return entity.getMapId();
        }
        String mapId = UUIDGenerator.getUUID();
        mapManagementEntity.setMapId(mapId);
        mapManagementEntity.setDelFlag(YNEnum.N.toString());
        mapManagementEntity.setCreateUser(PlatformSessionUtils.getUserId());
        if (mapManagementEntity.getUploader() == null) {
            String userJson = sUserService.getSUser(PlatformSessionUtils.getUserId());
            SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
            if (sUser != null) {
                mapManagementEntity.setUploader(sUser.getUserName());
            }
        }
        mapManagementEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        mapManagementEntity.setUploadTime(PlatformDateUtils.getCurrentTimestamp());
        if (mapManagementEntity.getProvince() != null && mapManagementEntity.getCity() != null && mapManagementEntity.getArea() != null) {
            String district = mapManagementEntity.getProvince() + "-" + mapManagementEntity.getCity() + "-" + mapManagementEntity.getArea();
            mapManagementEntity.setTaskDistrict(district);
        }
        mapManagementRepository.saveMap(mapManagementEntity);
        return mapId;
    }

    @Override
    public Map<String, Object> getById(String id) {
        MapManagementEntity mapManagementEntity = mapManagementRepository.getById(id);
//        AttachmentInfoEntity attach = attachmentInfoService.getAttach(mapManagementEntity.getAttachId());
//        Map<String, Object> map = new HashMap<>();
//        map.put("mapManagementEntity", mapManagementEntity);
//        map.put("attach", attach);
        String attachId = mapManagementEntity.getAttachId();
        String[] attahIds = attachId.split(",");//其中建筑物综合抗震能力评价图（区县、乡镇、格网）每种类型按不同烈度6-10保存多张图，附件ID用,分隔
        List<AttachmentInfoEntity> attachList = new ArrayList<>();
        for(int i=0;i<attahIds.length;i++){
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(attahIds[i]);
            attachList.add(attach);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("mapManagementEntity", mapManagementEntity);
        map.put("attachList", attachList);
        return map;
    }

    @Override
    public void deleteByIds(List<String> ids) {
        Timestamp timestamp = PlatformDateUtils.getCurrentTimestamp();
        mapManagementRepository.deleteByIds(ids, timestamp);
    }

    @Override
    public MapManagementEntity update(MapManagementEntity mapManagementEntity) {
        Timestamp timestamp = PlatformDateUtils.getCurrentTimestamp();
        String userId = PlatformSessionUtils.getUserId();
        mapManagementEntity.setUpdateTime(timestamp);
        mapManagementEntity.setUploadTime(timestamp);
        mapManagementEntity.setUpdateUser(userId);
        if (mapManagementEntity.getUploader() == null) {
            String userJson = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
            if (sUser != null) {
                mapManagementEntity.setUploader(sUser.getUserName());
            }
        }
        if (PlatformObjectUtils.isEmpty(mapManagementEntity.getDelFlag())) {
            mapManagementEntity.setDelFlag(YNEnum.N.toString());
        }
        return mapManagementRepository.update(mapManagementEntity);
    }

    @Override
    public Map<String, Object> queryMaps(MapManagementQueryParams queryParams, int curPage, int pageSize) {
        StringBuilder stringBuilder = new StringBuilder();
        if (queryParams.getProvince() != null) {
            stringBuilder.append(queryParams.getProvince());
        }
        if (queryParams.getCity() != null && !queryParams.getProvince().equals(queryParams.getCity())) {
            stringBuilder.append("-").append(queryParams.getCity());
        }
        if (queryParams.getArea() != null) {
            stringBuilder.append("-").append(queryParams.getArea());
        }
        queryParams.setTaskDistrict(stringBuilder.toString());
        Map<String, Object> map = mapManagementRepository.queryMaps(queryParams, curPage, pageSize);
        return map;
    }

    @Override
    public MapManagementEntity getByLabel(String taskId, String mapLabel) {
        return mapManagementRepository.getByLabel(taskId, mapLabel);
    }

    @Override
    public List<PreVo> getFuTask() {
        //只能查看到任务管理员、组长、组员及专家成员分配给自己的任务  查询自己所在小组关联的任务
        List<PreAssessTaskEntity> taskList = preAssessTaskRepository.getTaskListByUserId(PlatformSessionContext.getUserID());//查询部分任务信息，用于PreVo列表展示
        List<PreVo> preVoList = new ArrayList<>();
        if(PlatformObjectUtils.isNotEmpty(taskList)){
            ArrayList<PreAssessTaskEntity> list = taskList.stream().collect(
                    // 将集合先放到 treeSet 集合然后将他们转换成数组
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(task -> task.getTaskNum())))
                            , ArrayList::new)
            );
            list.forEach(entity->{
                PreVo vo = new PreVo();
                BeanUtils.copyProperties(entity,vo);
                vo.setTaskCodeAndTaskName(entity.getTaskNum() + "-" + entity.getTaskName());
                preVoList.add(vo);
            });
        }
        return preVoList;
//        List<PreVo> preVoList = preAssessTaskRepository.getFuTask();
//        if (preVoList != null && preVoList.size() > 0) {
//            for (PreVo preVo : preVoList) {
//                String taskNum = preVo.getTaskNum();
//                String taskName = preVo.getTaskName();
//                preVo.setTaskCodeAndTaskName(taskNum + "-" + taskName);
//            }
//        }
//        return preVoList;
    }


    @Override
    public String getPopulationPath(String taskId) {
        String label = "1";
        MapManagementEntity byLabe = mapManagementRepository.getByLabel(taskId, label);
        if (byLabe != null){
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(byLabe.getAttachId());
            String populationPath = attach.getFileDirId() + attach.getAttachPath();
            return populationPath;
        }
        return null;
    }

    @Override
    public String getEconomicsPath(String taskId) {
        String label = "2";
        MapManagementEntity byLabe = mapManagementRepository.getByLabel(taskId, label);
        if (byLabe != null){
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(byLabe.getAttachId());
            String economicsPath = attach.getFileDirId() + attach.getAttachPath();
            return economicsPath;
        }
        return null;
    }

    @Override
    public String getPathByLabel(String taskId, String mapLabel) {
        MapManagementEntity byLabe = mapManagementRepository.getByLabel(taskId, mapLabel);
        if (byLabe != null){
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(byLabe.getAttachId());
            String economicsPath = attach.getFileDirId() + attach.getAttachPath();
            return economicsPath;
        }
        return null;
    }

    @Override
    public Table<String,String,String> getPathByLabel1(String taskId) {
        List<MapManagementEntity> byLabe = mapManagementRepository.getByLabel(taskId);
        Table<String,String,String> map = TreeBasedTable.create();;
        if (PlatformObjectUtils.isNotEmpty(byLabe)){
            for (MapManagementEntity entity : byLabe) {
                String title = entity.getTitle();
                if(StringUtils.isBlank(entity.getTitle())){
                    title = "临时名称";
                }
                if("16".equals(entity.getMapLabel())){
                    System.out.println("111");
                }
                List<String> titleList = Arrays.asList(title.split(","));
                //List<String> pathList = new ArrayList<>();
                if(StringUtils.isNotBlank(entity.getAttachId())){
                    String[] split = entity.getAttachId().split(",");
                    if(split.length>0){
                        for(int i=0;i<split.length;i++){
                            AttachmentInfoEntity attach = attachmentInfoService.getAttach(split[i]);
                            //pathList.add(attach.getFileDirId() + attach.getAttachPath());
                            String path = "";
                            try{
                                String title1 = titleList.size()==split.length?titleList.get(i):"临时名称";
                                path = map.get(entity.getMapLabel(), title1);
                            }catch (ArrayIndexOutOfBoundsException e){
                                e.printStackTrace();
                            }
                            if(StringUtils.isBlank(path)){
                                map.put(entity.getMapLabel(),titleList.get(i),attach.getFileDirId() + attach.getAttachPath());
                            }
                        }
                    }
                }
            }
        }
        return map;
    }

    @Override
    public Map<String,String> getPathByLabel(String taskId) {
        List<MapManagementEntity> byLabe = mapManagementRepository.getByLabel(taskId);
        Map<String,String> map = new HashMap<>();;
        if (PlatformObjectUtils.isNotEmpty(byLabe)){
            for (MapManagementEntity entity : byLabe) {
                List<String> pathList = new ArrayList<>();
                if(StringUtils.isNotBlank(entity.getAttachId())){
                    String[] split = entity.getAttachId().split(",");
                    if(split.length>0){
                         for(String id:split){
                             AttachmentInfoEntity attach = attachmentInfoService.getAttach(id);
                             pathList.add(attach.getFileDirId() + attach.getAttachPath());
                         }
                         if(pathList.size()>0){
                             String join = String.join(",", pathList);
                             try{
                                 if(map.containsKey(entity.getMapLabel())){
                                     String path = map.get(entity.getMapLabel());
                                     path+=(","+(join));
                                     map.put(entity.getMapLabel(),path);
                                 }else{
                                     map.put(entity.getMapLabel(),join);
                                 }
                                 //map.put(entity.getMapLabel(),attach.getFileDirId() + attach.getAttachPath());
                             }catch (NullPointerException e){
                                 e.printStackTrace();
                             }
                         }
                    }
                }
            }
        }
        return map;
    }

    @Override
    public Map<String, String> getOtherPathByLabel(String taskId) {
        List<MapManagementEntity> byLabe = mapManagementRepository.getByLabel(taskId);
        Map<String,String> map = null;
        if (PlatformObjectUtils.isNotEmpty(byLabe)){
            map = new HashMap<>(byLabe.size());
            for (MapManagementEntity entity : byLabe) {
                AttachmentInfoEntity attach = attachmentInfoService.getAttach(entity.getAttachId());
                map.put(entity.getMapName(),attach.getFileDirId() + attach.getAttachPath());
            }
        }
        return map;
    }
}
